// designerStore

import first from 'lodash/first';
import get from 'lodash/get';
import { makeAutoObservable, toJS } from "mobx";
import { GoodsBaseData, GoodsData, RepeatType } from "types/type";
import textureManager from "../textureManager";
import initGoodsBaseData from "./initGoodsBaseData";
import perview3der from '../RightTop/PreView2D3D/perview3der';

class DesignerStore {

    constructor() {
        makeAutoObservable(this, {}, { deep: false });
    }

    // 加载中
    loadding = false;
    setLoadding(loadding) {
        this.loadding = loadding;
    }

    // 是否有更新
    needUpdateTime = 0;
    updataTime() {
        this.needUpdateTime++;
    }

    // 设计数据
    designData: GoodsData["productData"] = {
        color: "",
        colorValue: "#ffffff",
        designData: {},
        designThumbs: [], // 前后片的设计图
        designName: '',
        previewThumb: [],
        thumbs: [""],
        printArea: 'front', // (front,back,double)
        threadColor: '#ffffff', //缝线的颜色
    }
    setDesignData(designData: GoodsData["productData"]) {
        console.log('setDesignData', designData);
        this.designData = designData;
        this.threadColor = designData.threadColor;
        this.selectColor = designData.color || designData.colorValue;
        // 触发当前选事件,以及显示当前颜色值
        this.setActiveComponent(this.activeComponent);
    }
    // 设置缝线的颜色
    threadColor = "#ffffff";
    setThreadColor(threadColor) {
        this.designData.threadColor = threadColor;
        this.threadColor = threadColor;
        this.updataTime();
    }
    // 修改设计数据
    modifyDesignData(designData, name = this.activeComponent) {
        // this.updataTime();
        if (!this.switching && !this.loadding && this.designData && (name || this.activeComponent)) {
            // console.log("modifyDesignData", name, designData);
            this.designData.designData[name || this.activeComponent] = designData;
        }
    }

    // 修改缩略图
    modifyThumb(thumb = '', back_thumb = '') {
        this.designData.thumbs = [thumb, back_thumb];
    }

    // 底板数据
    goodsBaseData = initGoodsBaseData();
    //商品缩率图
    goodsThumb = '';
    // 工艺
    secondaryCraftName = "";
    //可设计的部位
    goodsBaseDataComponents: GoodsBaseData["data"]["components"] = [];
    setGoodsBaseData(goodsBaseData: GoodsBaseData) {
        this.goodsBaseData = goodsBaseData;
        this.goodsBaseDataComponents = toJS(goodsBaseData.data.components.filter((c) => c.enable));
        this.goodsThumb = goodsBaseData.data.thumbs[0];
        this.secondaryCraftName = goodsBaseData.secondaryCraftName;
        if (this.goodsBaseDataComponents[0]) {
            const activeComponent = this.goodsBaseDataComponents[0].key;
            this.setActiveComponent(activeComponent);
        }
        // 重置缝线为白色
        this.setThreadColor("#ffffff");

        // // 初始名字加号码的参数
        // const goodsSides = this.goodsBaseDataComponents.map((c) => c.key);
        // //需要支持的面
        // const allSide = [
        //     'front',
        //     'back',
        //     'left_front',
        //     'right_front',
        //     'left_back',
        //     'right_back',
        // ];
        // const initSide = first(allSide.filter((s) => goodsSides.includes(s)));
        // if (initSide) {
        //     designerStore.setAddName(designerStore.addName, initSide);
        //     designerStore.setAddNum(designerStore.addNum, initSide);
        // }
    }
    //判断是否有这个部位
    hasComponent(componentKey: string) {
        if (this.goodsBaseDataComponents.length > 0) {
            const keys = this.goodsBaseDataComponents.map((c) => c.key);
            if (keys.includes(componentKey)) {
                return true;
            }
        }
        return false;
    }
    // 当前选中的部位
    activeComponent = '';
    setActiveComponent(activeComponent) {
        if (this.goodsBaseDataComponents.length > 0) {
            if (this.hasComponent(activeComponent) && this.activeComponent !== activeComponent) {
                this.activeComponent = activeComponent;
            }
            if (["升华"].includes(this.secondaryCraftName)) {
                // 设置当前颜色值
                const componentDesignData = this.designData.designData[activeComponent];
                if (componentDesignData && componentDesignData.background) {
                    this.selectColorValue = componentDesignData.background;
                }
            } else if (["烫画", "直喷"].includes(this.secondaryCraftName)) {

            }
        }
    }

    // 切换部位中的标志位
    switching = false;
    setSwitching(value: boolean) {
        this.switching = value;
    }

    //选中上一次部位
    perComponet() {
        if (this.goodsBaseDataComponents.length > 1) {
            const keys = this.goodsBaseDataComponents.map((c) => c.key);
            const index = keys.indexOf(this.activeComponent);
            this.setActiveComponent(keys[(index + keys.length - 1) % keys.length]);
        }
    }
    //选中下一个部位
    nextComponet() {
        if (this.goodsBaseDataComponents.length > 1) {
            const keys = this.goodsBaseDataComponents.map((c) => c.key);
            const index = keys.indexOf(this.activeComponent);
            this.setActiveComponent(keys[(index + 1) % keys.length]);
        }
    }
    // 专注模式(以选中对象为中心放大画布)
    focusMode = false;
    setFocusMode(focusMode: boolean) {
        this.focusMode = focusMode;
    }
    //放大
    amplify = false;
    setAmplify(amplify: boolean) {
        this.amplify = amplify;
    }

    //保存中
    saveIng = false;
    setSaveIng(saveIng: boolean) {
        this.saveIng = saveIng;
    }

    // 当前颜色
    selectColor: string = "";
    selectColorValue: `#${string}` = "#ffffff";
    //设置商品颜色
    async setDesignColor(color: string = "", colorValue: `#${string}`, applyAll: boolean = false) {
        console.log('color', color, "colorValue", colorValue);
        this.selectColor = color;
        this.selectColorValue = colorValue;

        if (["升华"].includes(this.secondaryCraftName) && colorValue) {
            // 如果是局部印的话，需要修改所有的部位的颜色
            for (let componenName in this.designData.designData) {

                if (applyAll || componenName === this.activeComponent) {
                    this.designData.designData[componenName].background = colorValue;
                    const transparentCanvas = textureManager.getTransparentCanvas(componenName);
                    const texture = textureManager.getTexture(componenName);
                    const ctx = textureManager.getCtx(componenName);

                    // 把透明背景的纹理绘制到带背景的纹理上, 并绘制背景颜色
                    if (ctx) {
                        ctx.save();
                        ctx.fillStyle = colorValue || "#ffffff";
                        ctx.globalCompositeOperation = "source-over";
                        ctx.fillRect(0, 0, 1024, 1024);
                        ctx.restore();
                        ctx.drawImage(transparentCanvas, 0, 0, 1024, 1024);
                    }
                    if (texture) {
                        texture.needsUpdate = true;
                    }
                }
            }
        }
        this.designData.color = color;
        this.designData.colorValue = colorValue;
        this.updataTime();
    }

    //当前选中对象的id
    activeObjectId = '';
    setActiveObjectId(activeObjectId: string) {
        this.activeObjectId = activeObjectId;
    }

    //当前选中的对象的类型
    activeObjectType = '';
    setActiveObjectType(activeObjectType) {
        console.log("activeObjectType", activeObjectType);
        this.activeObjectType = activeObjectType;
    }

    // 对象旋转值
    rotation = 0;
    setRotation(rotation) {
        this.rotation = rotation;
    }

    //对象的平铺类型
    repeat: RepeatType = 'no_repeat';
    setRepeat(repeat: RepeatType) {
        this.repeat = repeat;
    }

    // 显示重复间距控制器
    showRepeatSpaceContorl = false;
    setShowRepeatSpaceContorl(showRepeatSpaceContorl) {
        this.showRepeatSpaceContorl = showRepeatSpaceContorl;
    }

    // 间距关联
    repeatSpacelink = true;
    setRepeatSpacelink(repeatSpacelink) {
        this.repeatSpacelink = repeatSpacelink;
        if (this.repeatSpacelink) {
            this.repeatSpaceY = this.repeatSpaceX;
        }
    }

    // 平铺的横向间距
    repeatSpaceX: number = 0;
    setRepeatSpaceX(repeatSpaceX: number) {
        this.repeatSpaceX = repeatSpaceX;
    }

    // 平铺的纵向间距
    repeatSpaceY: number = 0;
    setRepeatSpaceY(repeatSpaceY: number) {
        this.repeatSpaceY = repeatSpaceY;
    }

    // 图片的遮罩用的svg地址
    clipSvgUrl: string = '';
    setClipSvgUrl(clipSvgUrl: string) {
        this.clipSvgUrl = clipSvgUrl;
    }

    // 设置当前选中文字的字体
    fontFamily: string = '';
    setFontFamily(fontFamily: string) {
        this.fontFamily = fontFamily;
    }

    // 设置当前选中文字的大小
    fontSize: number = 20;
    setFontSize(fontSize: number) {
        this.fontSize = fontSize;
    }

    // 设置字体间距
    fontSpace: number = 0;
    setFontSpace(fontSpace: number) {
        this.fontSpace = fontSpace;
    }

    //设置文字弯曲
    bendDegree: number = 0;
    setBendDegree(bendDegree: number) {
        this.bendDegree = bendDegree;
    }

    // 设置字体行高
    lineHeight: number = 0;
    setLineHeight(lineHeight: number) {
        this.lineHeight = lineHeight;
    }

    //设置锁定状态
    lock: boolean = false;
    setLock(lock: boolean) {
        this.lock = lock;
    }

    //颜色拾取中(pc的功能)
    // colorPicker: boolean = false;
    // originColor: string = '#ffffff';
    // pickerColor: string = '#ffffff'; // 吸色工具拾取到的颜色
    // setColorPicker(colorPicker: boolean) {
    //     const { activeComponent, designData } = designerStore;
    //     if (colorPicker) {
    //         this.originColor = designData.designData[activeComponent].background || '#ffffff';
    //     }
    //     this.colorPicker = colorPicker;
    // }
    // setPickerColor(color) {
    //     this.pickerColor = color;
    // }

    // //涂鸦模式
    // graffiti: boolean = false;
    // setGraffiti(graffiti: boolean) {
    //     this.graffiti = graffiti;
    // }

    //------------------------名字加号码相关的状态
    // 名字的字体
    // nameFontFamily: fontManage.fontlist[0].id,
    // setNameFontFamily(nameFontFamily) {
    //     this.nameFontFamily = nameFontFamily;
    //     fontManage.loadFont([nameFontFamily]);
    //     const nameObject = designEditorRender._objects.find((o) => o.name === 'name');
    //     if (nameObject) {
    //         this.setFontFamily(nameFontFamily);
    //         nameObject.set({ fontFamily: nameFontFamily });
    //         designEditorRender.render();
    //     }
    // },

    //名字的颜色
    // nameColor: '#000000',
    // setNameColor(nameColor) {
    //     this.nameColor = nameColor;
    //     const nameObject = designEditorRender._objects.find(
    //         (o) => o.name === 'name',
    //     );
    //     if (nameObject) {
    //         if (this.activeObjectId === nameObject.id) {
    //             this.setPickerColor(nameColor);
    //         }
    //         nameObject.set({ fill: nameColor });
    //         designEditorRender.render();
    //     }
    // },
    //添加名字
    addName: boolean = false;
    //名字的正反面
    nameSide: string = 'front';
    // async setAddName(addName, nameSide) {
    //     this.addName = addName;
    //     this.nameSide = nameSide;
    //     this.setActiveComponent(nameSide);
    //     await new Promise((resolve) => setTimeout(resolve, 100));

    //     for (let side of ['front', 'back', 'left_front', 'right_front', 'left_back', 'right_back']) {
    //         const needAddName = addName && side === this.nameSide;
    //         const needRemoveName = !addName || side !== this.nameSide;

    //         // 需要添加的操作
    //         if (needAddName) {
    //             if (
    //                 side === this.activeComponent &&
    //                 !designEditorRender._objects.some((o) => o.name === 'name')
    //             ) {
    //                 const nameObject = designEditorRender.addText('名字', {
    //                     name: 'name',
    //                     fontSize: 200,
    //                     left: 1024,
    //                     top: 450,
    //                     fontFamily: this.nameFontFamily,
    //                     fill: this.nameColor,
    //                 });
    //                 nameObject.editable = false;
    //             } else if (
    //                 side !== this.activeComponent &&
    //                 this.designData.designData[side] &&
    //                 !this.design_data.designData[side].objects.some((o) => o.name === 'name')
    //             ) {
    //                 const fabricData = this.designData.designData[side];
    //                 if (fabricData) {
    //                     const nameObject = new FabricText('名字', {
    //                         name: 'name',
    //                         fontSize: 200,
    //                         left: 1024,
    //                         top: 450,
    //                         fontFamily: this.nameFontFamily,
    //                         fill: this.nameColor,
    //                     });
    //                     nameObject.editable = false;
    //                     fabricData.objects.push(nameObject.toJSON());
    //                     await textureManager.updataTextByFabricJSON(side, fabricData);
    //                     this.updataTime();
    //                 }
    //             }
    //         }

    //         //需要删除的操作
    //         if (needRemoveName) {
    //             if (
    //                 side === this.activeComponent &&
    //                 designEditorRender._objects.some((o) => o.name === 'name')
    //             ) {
    //                 const nameObject = designEditorRender._objects.find((o) => o.name === 'name');
    //                 if (nameObject) {
    //                     designEditorRender.remove(nameObject);
    //                 }
    //             } else if (
    //                 side !== this.activeComponent &&
    //                 this.designData.designData[side] &&
    //                 this.designData.designData[side].objects.some((o) => o.name === 'name')
    //             ) {
    //                 const fabricData = this.designData.designData[side];
    //                 if (fabricData) {
    //                     fabricData.objects = fabricData.objects.filter((o) => o.name !== 'name');
    //                     await textureManager.updataTextByFabricJSON(side, fabricData);
    //                     this.updataTime();
    //                 }
    //             }
    //         }
    //     }
    // },

    //号码的字体
    // numFontFamily: fontManage.fontlist[0].id,
    // setNumFontFamily(numFontFamily) {
    //     this.numFontFamily = numFontFamily;
    //     fontManage.loadFont([numFontFamily]);
    //     const nameObject = designEditorRender._objects.find((o) => o.name === 'num');
    //     if (nameObject) {
    //         this.setFontFamily(numFontFamily);
    //         nameObject.set({ fontFamily: numFontFamily });
    //         designEditorRender.render();
    //     }
    // },

    //号码的颜色
    numColor: string = '#000000';
    // setNumColor(numColor) {
    //     this.numColor = numColor;
    //     const numObject = designEditorRender._objects.find(
    //         (o) => o.name === 'num',
    //     );
    //     if (numObject) {
    //         if (this.activeObjectId === numObject.id) {
    //             this.setPickerColor(numColor);
    //         }
    //         numObject.set({ fill: numColor });
    //         designEditorRender.render();
    //     }
    // },
    //添加号码
    addNum: boolean = false;
    numSide: string = 'front'; //号码的正反面
    // async setAddNum(addNum, numSide) {
    //     this.addNum = addNum;
    //     this.numSide = numSide;
    //     this.setActiveComponent(numSide);
    //     await new Promise(resolve => setTimeout(resolve, 30));
    //     for (let side of ['front', 'back', 'left_front', 'right_front', 'left_back', 'right_back']) {
    //         const needAddNum = addNum && side === this.numSide;
    //         const needRemoveNum = !addNum || side !== this.numSide;

    //         // 需要添加的操作
    //         if (needAddNum) {
    //             if (
    //                 side === this.activeComponent &&
    //                 !designEditorRender._objects.some((o) => o.name === 'num')
    //             ) {
    //                 const numObject = designEditorRender.addText('00', {
    //                     name: 'num',
    //                     fontSize: 200,
    //                     left: 1024,
    //                     top: 450,
    //                     fontFamily: this.numFontFamily,
    //                     fill: this.numColor,
    //                 });
    //                 numObject.editable = false;
    //             } else if (
    //                 side !== this.activeComponent &&
    //                 this.designData.designData[side] &&
    //                 !this.design_data.designData[side].objects.some((o) => o.name === 'num')
    //             ) {
    //                 const fabricData = this.designData.designData[side];
    //                 if (fabricData) {
    //                     const numObject = new FabricText('00', {
    //                         name: 'num',
    //                         fontSize: 200,
    //                         left: 1024,
    //                         top: 450,
    //                         fontFamily: this.numFontFamily,
    //                         fill: this.numColor,
    //                     });
    //                     numObject.editable = false;
    //                     fabricData.objects.push(numObject.toJSON());
    //                     await textureManager.updataTextByFabricJSON(side, fabricData);
    //                     this.updataTime();
    //                 }
    //             }
    //         }

    //         //需要删除的操作
    //         if (needRemoveNum) {
    //             if (
    //                 side === this.activeComponent &&
    //                 designEditorRender._objects.some((o) => o.name === 'num')
    //             ) {
    //                 const numObject = designEditorRender._objects.find((o) => o.name === 'num');
    //                 if (numObject) {
    //                     designEditorRender.remove(numObject);
    //                 }
    //             } else if (
    //                 side !== this.activeComponent &&
    //                 this.designData.designData[side] &&
    //                 this.designData.designData[side].objects.some((o) => o.name === 'num')
    //             ) {
    //                 const fabricData = this.designData.designData[side];
    //                 if (fabricData) {
    //                     fabricData.objects = fabricData.objects.filter((o) => o.name !== 'num');
    //                     await textureManager.updataTextByFabricJSON(side, fabricData);
    //                     this.updataTime();
    //                 }
    //             }
    //         }
    //     }
    // },

    //预览名字和号码
    // async perViewNameNum(i, nameOrNum) {
    //     const nameNum = this.nameNumList[i];
    //     if (nameNum) {
    //         if (nameOrNum === 'name') {
    //             this.setActiveComponent(this.nameSide);
    //         } else if (nameOrNum === 'num') {
    //             this.setActiveComponent(this.numSide);
    //         }
    //         await new Promise((resolve) => setTimeout(resolve, 100));
    //         designEditorRender._objects.map((o) => {
    //             if (['name', 'num'].includes(o.name)) {
    //                 const text = new FabricText();
    //                 text.set(o);

    //                 if (o.name === 'name') {
    //                     o.set({ text: nameNum.name });
    //                 } else if (o.name === 'num') {
    //                     o.set({ text: String(nameNum.num) });
    //                 }

    //                 const w = text.getScaledWidth();
    //                 const h = text.getScaledHeight();
    //                 const scale = Math.min(
    //                     o.originWidth / w,
    //                     o.originHeight / h,
    //                 );

    //                 o.fontSize *= scale;

    //                 //如果是当前选中的对象就同步一下字体大小的参数
    //                 if (o.id === this.activeObjectId) {
    //                     this.setFontSize(o.fontSize);
    //                 }

    //                 if (o.name === 'name') {
    //                     o.set({ text: nameNum.name });
    //                 } else if (o.name === 'num') {
    //                     o.set({ text: String(nameNum.num) });
    //                 }
    //             }
    //         });
    //         designEditorRender.render();
    //         await new Promise((resolve) => setTimeout(resolve, 100));
    //         for (let side of [
    //             'front',
    //             'back',
    //             'left_front',
    //             'right_front',
    //             'left_back',
    //             'right_back',
    //         ]) {
    //             if (side !== this.activeComponent && this.designData.designData[side]) {
    //                 const fabricData = this.designData.designData[side];
    //                 if (fabricData) {
    //                     fabricData.objects.map((o) => {
    //                         if (o.name === 'name') {
    //                             o.text = nameNum.name;
    //                         } else if (o.name === 'num') {
    //                             o.text = String(nameNum.num);
    //                         }
    //                         if (['name', 'num'].includes(o.name)) {
    //                             const text = new FabricText();
    //                             text.set(o);
    //                             const w = text.getScaledWidth();
    //                             const h = text.getScaledHeight();
    //                             const scale = Math.min(o.originWidth / w, o.originHeight / h);
    //                             text.fontSize *= scale;
    //                             Object.assign(o, text.toJSON());
    //                         }
    //                     });
    //                     await textureManager.updataTextByFabricJSON(side, fabricData);
    //                     this.updataTime();
    //                 }
    //             }
    //         }
    //     }
    // },

    // //名字号码列表
    // nameNumList: [],
    // setNameNumList(nameNumList) {
    //     this.nameNumList = nameNumList;
    // },
    // addNameNum() {
    //     const { goodsData } = this;
    //     if (goodsData) {
    //         const sizePrice = toJS(goodsData.sizePrice) || [];
    //         const size = get(sizePrice, [0, 'size']);
    //         this.nameNumList = [...this.nameNumList, { name: '名字', num: '00', size }];
    //     }
    // },
    // delNameNum(i) {
    //     this.nameNumList.splice(i, 1);
    //     this.nameNumList = [...this.nameNumList];
    // },
    // updataNameNum(i, p) {
    //     this.nameNumList.map((nameNum, ii) => {
    //         if (ii === i) {
    //             Object.assign(nameNum, p);
    //         }
    //     });
    //     this.nameNumList = [...this.nameNumList];
    // },

    // //编辑名字号码
    // editorNameNum: false,
    // setEditorNameNum(editorNameNum) {
    //     this.editorNameNum = editorNameNum;
    // },

    //保存 有设计id有传入设计id
    async save(id = '') {
        // const { thumbs, previewThumb } = await perview3der.getAllImage();
        // this.designData.thumbs = await Promise.all(thumbs.map((thumb) => {
        //     return new Promise(async (resolve, reject) => {
        //         // 获取本地文件的信息
        //         const fileInfo = await Taro.getFileInfo({
        //             filePath: thumb,
        //         });
        //         const url = await utilsApi.uploadOss({ path: thumb, size: fileInfo.size });
        //         console.log('上传oss', url);
        //         resolve(url);
        //     });
        // }));

        // this.designData.previewThumb = await Promise.all(previewThumb.map((thumb) => {
        //     return new Promise(async (resolve, reject) => {
        //         // 获取本地文件的信息
        //         const fileInfo = await Taro.getFileInfo({
        //             filePath: thumb,
        //         });
        //         const url = await utilsApi.uploadOss({ path: thumb, size: fileInfo.size });
        //         resolve(url);
        //     });
        // }));

        const hasFront = (get(this.designData.designData, ['front', 'objects', 'length']) || 0) > 0;
        const hasBack = (get(this.designData.designData, ['back', 'objects', 'length']) || 0) > 0;

        if (hasFront && hasBack) {
            this.designData.printArea = 'double';
        } else if (!hasFront && hasBack) {
            this.designData.printArea = 'back';
        } else {
            this.designData.printArea = 'front';
        }
        console.log('设计数据', this.designData);
        try {
            // const result = await designApi.saveProduct(this.designData);
            // const result = await designApi.saveProduct();
            // id = result.id;
        } catch (error) {
            console.log('保存失败', error);
        }
        return id;
    }

}

const designerStore = new DesignerStore();

export default designerStore;//activeObjectType